<!-- 极限大概在生成400行, 20列 -->

<template>
  <div class="container" ref="container"></div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, toRaw } from 'vue'
import {
  createUniver,
  defaultTheme,
  FUniver,
  LocaleType,
  merge,
  type IWorkbookData,
} from '@univerjs/presets'
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core'
import UniverPresetSheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN'
import '@univerjs/presets/lib/styles/preset-sheets-core.css'
import { SheetRenderer, type IFormDataIntervalDto } from './CmpSheets'
import { UniverWatermarkPlugin } from '@univerjs/watermark'
import { IWatermarkTypeEnum } from '@univerjs/engine-render'

import '@univerjs/watermark/facade'

interface IProp {
  /**
   * 电子表格数据
   */
  workbookData?: Partial<IWorkbookData>

  /**
   * 后台数据
   */
  data?: Array<IFormDataIntervalDto>
}

const props = defineProps<IProp>()

const container = ref<HTMLElement | null>(null)
const univerAPIRef = ref<FUniver | null>(null)

const init = () => {
  if (univerAPIRef.value) {
    toRaw(univerAPIRef.value)?.dispose()
    univerAPIRef.value = null
  }

  const { univerAPI } = createUniver({
    locale: LocaleType.ZH_CN,
    locales: {
      [LocaleType.ZH_CN]: merge({}, UniverPresetSheetsCoreZhCN),
    },
    plugins: [UniverWatermarkPlugin],
    theme: defaultTheme,
    presets: [
      UniverSheetsCorePreset({
        container: container.value!,
      }),
    ],
  })

  univerAPI.createWorkbook(props.workbookData!)
  univerAPI.addWatermark(IWatermarkTypeEnum.Text, {
    x: 0,
    y: 0,
    spacingX: 200,
    spacingY: 200,
    rotate: -45,
    opacity: 0.2,
    content: '济医附医',
    repeat: true,
    fontSize: 10,
    color: '#000000',
    bold: true,
    italic: true,
    direction: 'ltr',
  })

  console.log(`output->univerAPI`, univerAPI)

  //#region 传递表格实例
  univerAPIRef.value = univerAPI;

  // 如果 传递了需要生成的数据则进行渲染
  if (props.data && props.data?.length > 0) new SheetRenderer().render(univerAPI, props.data)

  //#endregion
}

// watchEffect(() => {
//   if (props.workbookData) {
//     init()
//   }
// })

// watchEffect(() => {
//   if (props.data && props.data.length > 0) {
//     init()
//   }
// })

onMounted(() => {
  init()
})

// 释放组件
onBeforeUnmount(() => {
  toRaw(univerAPIRef.value)?.dispose()
  univerAPIRef.value = null
})

// 导出组件实例
defineExpose({
  getUniverAPIRef: () => univerAPIRef.value,
  univerAPIRef: univerAPIRef,
})
</script>

<style scoped>
.container {
  height: 95%;
}
</style>
